package com.hrm.controller;

import com.alibaba.fastjson.JSONObject;
import com.hrm.dto.Response;
import com.hrm.dto.ResponseDTO;
import com.hrm.entity.Staff;
import com.hrm.service.LoginService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 登录注册接口
 *
 */
@RestController
public class LoginController {

    @Resource
    private LoginService loginService;

    @PostMapping("/login")
    public ResponseDTO login(@RequestBody Staff staff) {
        return this.loginService.login(staff);
    }

    /**
     * 通过账号查找员工
     * @param code
     * @return
     */
    @GetMapping("/find")
    public ResponseDTO findByCode(String code){
        return this.loginService.findByCode(code);
    }

    /**
     * 以get方式调用对方接口方法
     * @param
     */
    @GetMapping
    public ResponseDTO doGet() {
        String pathUrl = "http://api.k780.com/?app=weather.realtime&cityNm=成都&ag=today,futureDay,lifeIndex,futureHour&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
        StringBuffer sb = new StringBuffer();
        try {
            URL realUrl = new URL(pathUrl);

            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);

            //请求方式为post
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);//自动处理重定向

            // 增加请求头 start
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 增加请求头 end
            connection.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            reader.close();
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();

        }

        JSONObject jsonObj = JSONObject.parseObject(sb.toString());
        return Response.success(jsonObj);
    }
}
